﻿package com.vinyl.app
{
	import flash.display.MovieClip;
	import flash.events.*;

	import com.vinyl.command.*;
	
	public class Activity 
	{
		private var _c:Number;
		private var _scope: MovieClip;
		public var listeners: Array;
		
		public function Activity( $scope: MovieClip )
		{
			_c = 0;
			_scope = $scope;	
			listeners = new Array();
			start();
		}
		
		public function addTimelineListener( $exe: ICommand ): void
		{		
			listeners.push( $exe )
			if ( listeners.length == 1 ) resume();
		}
		
		public function removeTimelineListener( $exe: ICommand ): Boolean
		{
			for ( var i:Number = 0; i<listeners.length; i++ )
			{
				if ( listeners[i] == $exe )
				{
					listeners.splice(i,1);
					if ( listeners.length == 0 ) pause();
					return true;
				}
			}
			return false;
		}
		
		public function pause(): void
		{
			stop();
		}
		
		public function resume(): void
		{
			start();
		}
		
		private function start(): void
		{
			if ( listeners.length == 0 ) return;
			if ( _scope.hasEventListener( Event.ENTER_FRAME ) ) return;
			_scope.addEventListener( Event.ENTER_FRAME, run );
		}
		
		private function run( $event: Event):void
		{	
			for (var i:Number = 0; i < listeners.length; i++)
			{
				ICommand( listeners[i] ).execute();
			}
			_c++;
		}
		
		private function stop(): void
		{
			_scope.removeEventListener( Event.ENTER_FRAME, run );
		}
		
		public function toString():String
		{
			return "[Object Activity]";
		}
	}
}